package com.houtai.controller.train;


import com.aliyun.openservices.oss.model.ObjectMetadata;
import com.houtai.authority.Authority;
import com.houtai.authority.AuthorityType;
import com.houtai.base.RetInfo;
import com.houtai.base.WangEditor;
import com.houtai.bean.TdTrain;
import com.houtai.bean.TdTrainApply;
import com.houtai.bean.TsJzAdmin;
import com.houtai.bean.dto.train.TdTrainPage;
import com.houtai.bean.dto.train.apply.TdTrainApplyPage;
import com.houtai.common.Contant;
import com.houtai.common.oss.OssUtil;
import com.houtai.common.util.ExcelUtil;
import com.houtai.service.dict.DictService;
import com.houtai.service.funcion.FuncionService;
import com.houtai.service.train.TrainService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by lizhun on 2017/7/19.
 */
@Controller
@RequestMapping(value = {"v5"})
public class TrainController {
    @Resource
    private TrainService trainService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Resource
    private FuncionService funcionService;
    @Resource
    private DictService dictService;
    /**
     * @Purpose  分页加载培训
     * @version  1.0
     * @author   lizhun
     * @param    request
     * @return   RetInfo
     */
    @RequestMapping(value="/train/apply/list")
    @Authority(AuthorityType.Login)
    public ModelAndView apply(HttpServletRequest request, TdTrainApplyPage page){
        ModelAndView mv = new ModelAndView("train/apply");
        TsJzAdmin tsJzAdmin = (TsJzAdmin) redisTemplate.opsForValue().get(request.getParameter("token")) ;
        mv.addObject("retInfo", trainService.findTdTrainApplyPage(page, request));
        mv.addObject("token", request.getParameter("token"));
        return mv;
    }
    /**
     * @Purpose  分页加载培训
     * @version  1.0
     * @author   lizhun
     * @param    request
     * @return   RetInfo
     */
    @RequestMapping(value="/train/list")
    @Authority(AuthorityType.Login)
    public ModelAndView list(HttpServletRequest request, TdTrainPage page){
        ModelAndView mv = new ModelAndView("train/list");
        mv.addObject("class_way", dictService.findTsJzDict("class_way"));
        mv.addObject("train_cate", dictService.findTsJzDict("train_cate"));
        TsJzAdmin tsJzAdmin = (TsJzAdmin) redisTemplate.opsForValue().get(request.getParameter("token")) ;
        mv.addObject("retInfo", trainService.findTrainPage(page, request));
        mv.addObject("token", request.getParameter("token"));
        mv.addObject("father_id", request.getParameter("father_id"));
        mv.addObject("funcions", funcionService.findSonFuncion(tsJzAdmin, Integer.valueOf(request.getParameter("father_id"))));
        return mv;
    }
    /**
     * @Purpose  跳转到添加培训页面
     * @version  1.0
     * @author   lizhun
     * @param    request
     * @return   RetInfo
     */
    @RequestMapping(value="/train/to/add")
    @Authority(AuthorityType.Login)
    public ModelAndView index(HttpServletRequest request){
        ModelAndView mv = new ModelAndView("train/add");
        mv.addObject("token", request.getParameter("token"));
        mv.addObject("class_way", dictService.findTsJzDict("class_way"));
        mv.addObject("train_cate", dictService.findTsJzDict("train_cate"));
        return mv;
    }
    /**
     *上传banner图片
     * @param frontFile
     * @return
     */
    @RequestMapping(value = "/train/img" )
    @ResponseBody
    public Map<String, String> img(@RequestParam(value = "frontFile", required = true) MultipartFile frontFile)throws Exception{
        Map<String, String>  map = new HashMap<>();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddhhmmssS", Locale.CHINA);

        String frontFileName = frontFile.getOriginalFilename().substring(frontFile.getOriginalFilename().lastIndexOf(".") + 1);
        String imgName = formatter.format(new Date(System.currentTimeMillis()));
        String frontSavePath = Contant.FILE_IMG+"/" + "train/" + imgName + "." + frontFileName;
        ObjectMetadata frontMetadata = new ObjectMetadata();

        InputStream inputStream = frontFile.getInputStream();
        frontMetadata.setContentLength(inputStream.available());
        OssUtil.uploadInputStream(inputStream, frontMetadata, frontSavePath);
        map.put("mark", "0");
        map.put("tip", Contant.DOMAIN +  Contant.FILE_IMG+"/"+"train"+"/"+imgName + "." + frontFileName);
        map.put("obj", imgName);

        return map;
    }
    /**
     *上传banner图片
     * @param frontFile
     * @return
     */
    @RequestMapping(value = "/train/fileImg" )
    @ResponseBody
    public WangEditor fileImg(@RequestParam(value = "frontFile", required = true) MultipartFile frontFile)throws Exception{
        Map<String, String> map = new HashMap<>();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddhhmmssS", Locale.CHINA);

        String frontFileName = frontFile.getOriginalFilename().substring(frontFile.getOriginalFilename().lastIndexOf(".") + 1);
        String imgName = formatter.format(new Date(System.currentTimeMillis()));
        String frontSavePath = Contant.FILE_IMG+"/" + "train/" + imgName + "." + frontFileName;
        ObjectMetadata frontMetadata = new ObjectMetadata();

        InputStream inputStream = frontFile.getInputStream();
        frontMetadata.setContentLength(inputStream.available());
        OssUtil.uploadInputStream(inputStream, frontMetadata, frontSavePath);

        String[] str = { Contant.DOMAIN +  Contant.FILE_IMG+"/"+"train"+"/"+imgName + "." + frontFileName};
        WangEditor we = new WangEditor(str);
        return we;
    }
    /**
     * @Purpose   添加培训
     * @param     tdTrain
     * @version   1.0
     * @author    李准
     * @time      2017-08-19
     * @return    RetInfo
     */
    @RequestMapping(value = "/train/add", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    @Authority(AuthorityType.Login)
    public RetInfo insert(@Valid TdTrain tdTrain, BindingResult result, HttpServletRequest request) {
        RetInfo retInfo = new RetInfo();
        if (result.hasErrors()) {
            List<FieldError> err = result.getFieldErrors();
            FieldError fe = err.get(0);
            retInfo.setMark("1");
            retInfo.setTip(fe.getDefaultMessage());
        } else {
            retInfo = trainService.insertTdTrain(tdTrain, request);
        }
        return retInfo;
    }
    /**
     * @Purpose  跳转到更新培训页面
     * @version  1.0
     * @author   lizhun
     * @param    request
     * @return   RetInfo
     */
    @RequestMapping(value="/train/to/update")
    @Authority(AuthorityType.Login)
    public ModelAndView index(HttpServletRequest request, Integer train_id){
        ModelAndView mv = new ModelAndView("train/update");
        TdTrain tdTrain = trainService.findTdTrainById(train_id);
        mv.addObject("token", request.getParameter("token"));
        mv.addObject("train", tdTrain);
        mv.addObject("class_way", dictService.findTsJzDict("class_way"));
        mv.addObject("train_cate", dictService.findTsJzDict("train_cate"));
        return mv;
    }
    /**
     * @Purpose   更新培训
     * @param     tdTrain
     * @version   1.0
     * @author    李准
     * @time      2017-08-19
     * @return    RetInfo
     */
    @RequestMapping(value = "/train/update", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    @Authority(AuthorityType.Login)
    public RetInfo update(@Valid  TdTrain tdTrain, BindingResult result, HttpServletRequest request) {
        RetInfo retInfo = new RetInfo();
        if (result.hasErrors()) {
            List<FieldError> err = result.getFieldErrors();
            FieldError fe = err.get(0);
            retInfo.setMark("1");
            retInfo.setTip(fe.getDefaultMessage());
        } else {
            retInfo = trainService.updateTdTrain(tdTrain, request);
        }
        return retInfo;
    }
    /**
     * @Purpose   更新培训状态
     * @param     train_id
     * @version   1.0
     * @author    李准
     * @time      2017-08-19
     * @return    RetInfo
     */
    @RequestMapping(value = "/train/update/state", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    @Authority(AuthorityType.Login)
    public RetInfo valid(Integer train_id,  HttpServletRequest request) {

        return trainService.deleteTdTrain(train_id, request);
    }
    /**
     * 导出报表
     * @return
     */
    @RequestMapping(value = "/train/apply/export")
    @ResponseBody
    public void export(HttpServletRequest request,HttpServletResponse response,TdTrainApplyPage page) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        //excel标题
        String[] title = {"id","时间","姓名","电话"};
        TdTrain tdTrain = trainService.findTdTrainById(page.getTrain_id());
        List<TdTrainApply> datas = trainService.findTdTrainApplyExport(page);
        //excel文件名
        String fileName = tdTrain.getTrain_title()+ "-" + "报名信息" + ".xls";
        //sheet名
        String sheetName = "报名列表";
        int size = datas.size();
        String[][] content = new String[size][100];
        for (int i = 0; i < size; i++) {
            content[i][0] = "" + datas.get(i).getApply_id();
            content[i][1] = format.format(datas.get(i).getAdd_time());
            content[i][2] = datas.get(i).getName();
            content[i][3] =  datas.get(i).getPhone_no();



        }

        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);

        //响应到客户端
        try {
            this.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //发送响应流方法
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(),"ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

}
